//
//  Album.m
//  05-UI2
//
//  Created by Snow on 16/7/21.
//  Copyright © 2016年 Snow. All rights reserved.
//

#import "Album.h"
#import "UIImageView+WebCache.h"
@interface Album ()<UIScrollViewDelegate>

@property (nonnull, nonatomic, strong) UIScrollView *scrollView;
@property (nonatomic, strong) NSMutableArray *mArr;
@end

@implementation Album
- (instancetype)initWithFrame:(CGRect)frame images:(NSArray <NSString *>*)images
{
    self = [super initWithFrame:frame];
    if (self) {
        [self configWithFrame:frame images:(NSArray *)images];
    }
    return self;
}
- (void)configWithFrame:(CGRect)frame images:(NSArray *)images
{
    self.mArr = [NSMutableArray arrayWithArray:images];
    [self.mArr insertObject:[images lastObject] atIndex:0];
    [self.mArr addObject:[images firstObject]];
    self.scrollView = [[UIScrollView alloc] initWithFrame:frame];
    self.scrollView.delegate = self;
    self.scrollView.pagingEnabled = YES;
    self.scrollView.contentOffset = CGPointMake(frame.size.width, 0);
    self.scrollView.showsHorizontalScrollIndicator = NO;
    self.scrollView.contentSize = CGSizeMake(frame.size.width * _mArr.count, frame.size.height);
    [self addSubview:self.scrollView];
    for (int i = 0; i < _mArr.count; i++) {
        UIImageView *imageView = [[UIImageView alloc] initWithFrame:frame];
        NSURL *url = [NSURL URLWithString:_mArr[i]];
        [imageView sd_setImageWithURL:url];
        UIScrollView *scrollSmall = [[UIScrollView alloc] initWithFrame:CGRectMake(frame.size.width * i, 0, frame.size.width, frame.size.height)];
        scrollSmall.delegate = self;
        scrollSmall.minimumZoomScale = 0.5;
        scrollSmall.maximumZoomScale = 2.0;
        scrollSmall.contentSize = CGSizeMake(frame.size.width, frame.size.height);
        [scrollSmall addSubview:imageView];
        [_scrollView addSubview:scrollSmall];
    }

}
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
{
    if (scrollView == _scrollView) {
        
        if (scrollView.contentOffset.x / self.frame.size.width > _mArr.count - 2 ) {
            scrollView.contentOffset = CGPointMake(self.frame.size.width, 0);
        } else if (scrollView.contentOffset.x / self.frame.size.width < 1)
        {
            scrollView.contentOffset = CGPointMake(self.frame.size.width * (_mArr.count - 2), 0);
        }
        for (UIScrollView *scroll in scrollView.subviews) {
            if ([scroll isKindOfClass:[UIScrollView class]]) {
                
                scroll.zoomScale = 1.0;
            }
        }
        
    }
}
- (UIView *)viewForZoomingInScrollView:(UIScrollView *)scrollView
{
    return  [scrollView.subviews objectAtIndex:scrollView.contentOffset.x / self.frame.size.width ];
}


@end
